import methods from "./methods.js";

export const BASE_URL = 'https://zcfk.webwing.cn:52319/sshb'; //打包线上

// export const BASE_URL = 'http://192.168.31.83:8090/sshb'; //公司
export const CLIENT_ID = '450620e00fa10e1d939048eb20475bab'; // 只用于访客小程序

/**
 * 获取存储的token
 * @returns {string} token值或空字符串
 */
export const getToken = () => uni.getStorageSync('token');


/**
 * 封装 uni.request
 * @param {string} url 接口路径
 * @param {object} data 请求参数
 * @param {string} method 请求方法 GET/POST/PUT
 * @param {boolean} isShowLoading 是否显示 loading，默认 true
 * @returns {Promise}
 */

// 记录是否已执行过againSet
let isFirstTokenRequest = true;
let LinkLong = 5;
let index = 0;

function request(url, data = {}, method = 'GET', isShowLoading = true) {
	const token = getToken();
	const header = {
		'content-type': 'application/json',
		...(token ? {
			authorization: 'Bearer ' + token
		} : {}),
		clientId: CLIENT_ID
	};

	if (!token) {
		return new Promise((resolve, reject) => {
			setTimeout(() => {
				request(url, method, data, isShowLoading).then(result => {
					resolve(result)
				})
			}, 300)
		})
	} else {
		// 只有首次有token的请求才执行
		if (isFirstTokenRequest) {
			methods.againSet()
			isFirstTokenRequest = false;
		}
	}




	if (isShowLoading) {
		uni.showLoading({
			title: '加载中...',
			mask: true,
		});
	}

	return new Promise((resolve, reject) => {
		uni.request({
			url: BASE_URL + url, // 使用封装的BASE_URL
			data,
			method,
			header,
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300) {
					if (res.data.code == 200) {
						resolve(res.data);
					} else if (res.data.code == 401) {
						index++
						if (index < LinkLong) {
							methods.login().then(res => {
								request(url, method, data, isShowLoading).then(result => {
									resolve(result)
								})
							})
						} else {
							uni.showToast({
								title: '网络出错了,稍后再试~',
								icon: 'none'
							});
							index = 0
						}
					} else {
						resolve(res.data);
					}
				} else {
					uni.showToast({
						title: '稍后再试~',
						icon: 'none'
					});
					reject(res.errMsg || '网络出错了,稍后再试~');
				}
			},
			fail(err) {
				uni.showToast({
					title: '网络异常',
					icon: 'none'
				});
				reject(err);
			},
			complete() {
				if (isShowLoading) {
					uni.hideLoading();
				}
			},
		});
	});
}

// GET 请求封装
export function $get(url, data = {}, isShowLoading = true) {
	return request(url, data, 'GET', isShowLoading);
}

// POST 请求封装
export function $post(url, data = {}, isShowLoading = true) {
	return request(url, data, 'POST', isShowLoading);
}

// PUT 请求封装
export function $put(url, data = {}, isShowLoading = true) {
	return request(url, data, 'PUT', isShowLoading);
}